﻿using Cheems.Interface.Media;
using Cheems.Interface.Models.Media;
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;

namespace Cheems.Service.Media
{
    /// <summary>
    /// 声音播放服务
    /// </summary>
    public class SoundService : ISound
    {
        private readonly HashSet<Task> _playTasks = new HashSet<Task>();

        // 播放一次音频（允许同时播放多个）
        public async Task PlayOnceAsync(string soundFilePath)
        {
            var playTask = Task.Run(() =>
            {
                using (var audioFileReader = new AudioFileReader(soundFilePath))
                using (var outputDevice = new WaveOutEvent())
                {
                    outputDevice.Init(audioFileReader);
                    outputDevice.Play();
                    while (outputDevice.PlaybackState == PlaybackState.Playing)
                    {
                        // 等待音频播放完成
                        Task.Delay(100).Wait();
                    }
                }
            });

            lock (_playTasks)
            {
                _playTasks.Add(playTask);
            }

            await playTask; // 等待当前播放任务完成
        }

        // 播放指定时长的音频
        public async Task PlayForDurationAsync(double duration, string soundFilePath)
        {
            var playTask = Task.Run(() =>
            {
                using (var audioFileReader = new AudioFileReader(soundFilePath))
                using (var outputDevice = new WaveOutEvent())
                {
                    outputDevice.Init(audioFileReader);
                    outputDevice.Play();
                }
            });

            await Task.Delay(TimeSpan.FromSeconds(duration)); // 播放指定时长后停止
        }

        // 获取音频时长
        private int GetSoundDuration(string soundFilePath)
        {
            using (var audioFileReader = new AudioFileReader(soundFilePath))
            {
                return (int)audioFileReader.TotalTime.TotalSeconds; // 获取音频的实际时长
            }
        }

        public async Task PlayFixedAudio(AudioLibrary audioLibrary)
        {
            switch (audioLibrary)
            {
                case AudioLibrary.btn_01:
                    await PlayOnceAsync(Path.Combine(Directory.GetCurrentDirectory(), "Assets/CheemsService/Audios/btn_01.wav"));
                    break;
                case AudioLibrary.btn_02:
                    await PlayOnceAsync(Path.Combine(Directory.GetCurrentDirectory(), "Assets/CheemsService/Audios/btn_02.wav"));
                    break;
            }
        }

        public void WaitForAllTasksToFinish()
        {
            Task.WhenAll(_playTasks).Wait();
        }
    }
}
